package workers

import (
	"black_mamba/global"
	"fmt"
	"gitee.com/wengo/go-amazon"
	"gitee.com/wengo/go-mamba"
	"github.com/PuerkitoBio/goquery"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"regexp"
	"time"
)

type RankWorker struct {
	Worker
	//FeedBackCallback func(int) int
}

func NewRankWorker() *RankWorker {
	return &RankWorker{
		Worker{
			Topic: "rank",
		},
	}
}

func (d *RankWorker) Execute(data map[string]interface{}) (ret interface{}) {
	/*
		   流程
		    1.访问首页
			2.新建收货地址，新建信用卡
			3.打开Listing
			4.加入购物车
			5.结账
			6.选择地址
			7.选择信用卡
			8.建立订单
	*/

	//defer func() {
	//	//可以打印错误信息
	//	//recover()
	//	//fmt.Println(recover())
	//
	//	//没有错就不要打印
	//	if err := recover(); err != nil { //产生了panic异常
	//		stackStr := string(debug.Stack())
	//		utils.WriteFile("error.log", fmt.Sprintf("%s\n%s\n", err, stackStr))
	//	}
	//}()

	var resp *mamba.Response
	var document *goquery.Document
	var err error
	var responsePath string
	website := data["website"].(string)
	//code := "us"
	amz := amazon.NewAmazon(amazon.Settings{
		//JA3:       "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-21,29-23-24,0",
		//UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
		JA3:       "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-21,29-23-24,0",
		UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36",
		BaseUri:   fmt.Sprintf("https://%s", website),
		//BaseUri:     "https://www.amazon.com",
		Header:      nil,
		Cookies:     nil,
		Debug:       false,
		DebugLength: 0,
		Proxy:       fmt.Sprintf("http://%s:%s@http-dynamic.xiaoxiangdaili.com:10030", global.BM_CONFIG.Section("proxy").Key("username").Value(), global.BM_CONFIG.Section("proxy").Key("password").Value()),
	})

	for {
		switch {
		case resp == nil: // 首页
			resp, document, err = amz.Navigate("/")
		case responsePath == "/":
			//var postalCode string
			//zipCode, _ := global.BM_API.GetZipCode(code, global.BM_CONFIG.Section("basic").Key("serialNumberCiphertext").Value())
			//postalCode = zipCode.ZipCode

			resp, err = amz.ChangeAddress(document, "10001")
			if err != nil {
				return
			} else {
				if gjson.Get(resp.String(), "address.zipCode").String() == "" {
					resp, document, err = amz.Navigate("/")
					continue
				}
			}

			resp, document, err = amz.Navigate("/deals?ref_=nav_cs_gb")
			if err != nil {
				fmt.Println("error")
				return
			}
		case responsePath == "/deals":
			ioutil.WriteFile("rank.html", resp.Body(), 0644)
			if err != nil {

			} else {

				matcher := regexp.MustCompile(`'slot-15', ([^\r\n]+})`)
				result := matcher.FindAllStringSubmatch(resp.String(), -1)
				//fmt.Println(len(gjson.Get(result[0][1], "prefetchedData.dcsGetDealMetadata.sortedDealIDs").Array()), gjson.Get(result[0][1], "prefetchedData.dcsGetDealMetadata.sortedDealIDs").Array())
				var deals []gjson.Result
				if len(gjson.Get(result[0][1], "prefetchedData.dcsGetDealMetadata.sortedDealIDs").Array()) == 0 {
					deals = gjson.Get(result[0][1], "prefetchedData.aapiSearchDeals.entity.rankedDeals.#.resource.url").Array()
				} else {
					deals = gjson.Get(result[0][1], "prefetchedData.dcsGetDealMetadata.sortedDealIDs").Array()
					fmt.Println(deals)
				}

				//for _, deal := range deals {
				//	s := strings.Split(deal.String(), "/")
				//	fmt.Print(s[len(s)-1])
				//	fmt.Print(" ")
				//}

				//fmt.Println(deals)
				//if len(gjson.Get(result[0][1], "prefetchedData.dcsGetDealMetadata.sortedDealIDs").Array()) == 0 {
				//	fmt.Println(ioutil.WriteFile("rank_error.html", resp.Body(), 0644))
				//}
				//var deals = make(map[string][]string)
				//if len(result) > 0 {
				//	for _, item := range gjson.Get(result[0][1], "prefetchedData.aapiGetDealsList.0.entities.#.entity.details.entity").Array() {
				//		if gjson.Get(item.String(), "type").String() == "BEST_DEAL" {
				//			uri := strings.Split(gjson.Get(item.String(), "landingPage.url").String(), "/")
				//			deals[gjson.Get(item.String(), "endTime.value").String()] = append(deals[gjson.Get(item.String(), "endTime.value").String()], uri[len(uri)-1])
				//		}
				//	}
				//}
				//
				//var bestDeals []string
				//for _, value := range deals {
				//	if len(value) > 10 {
				//		bestDeals = value
				//	}
				//}
				//fmt.Println(bestDeals)
				return

				time.Sleep(20 * time.Second)
				//time.Sleep(600 * time.Second)
				resp, _, err = amz.Navigate("/deals?ref_=nav_cs_gb")
			}
		}

		if resp != nil {
			responsePath = resp.RawResponse.Request.URL.Path
		}
	}

}
